﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace FierceWar
{
	public class EditMapScreen : BuildMapScreen
	{
		public EditMapScreen(GameResources resources, List<EventHandler> screenEvents)
			: base(resources, screenEvents)
		{
		}

		#region Methods.
		#region Load map from file.
		public void LoadMap(string fileName)
		{
			StreamReader sr = null;
			try
			{
				sr = File.OpenText("Map/" + fileName);
				Models.Clear();
				Roads.Clear();
				string line = null;
				while ((line = sr.ReadLine()) != null)
				{
					string[] values = (line.TrimEnd()).Split(new char[] { ' ' });

					// Check valid input string.
					if (values.Length < 10)
					{
						for (int i = values.Length; i <= 10; i++)
						{
							values[i] = "0";
						}
					}

					// Load type of model.
					int type = Convert.ToInt32(values[0]);
					// Create new model.
					ElementalModel model = new ElementalModel(Resources.Content,
						(ModelType)type);
					// Load model's position.
					model.Position = new Vector3((float)Convert.ToDouble(values[1]),
						(float)Convert.ToDouble(values[2]),
						(float)Convert.ToDouble(values[3]));
					// Load model's scale vector.
					model.Scale = new Vector3((float)Convert.ToDouble(values[4]),
						(float)Convert.ToDouble(values[5]),
						(float)Convert.ToDouble(values[6]));
					// Load model's rotation vector.
					model.Rotation = new Vector3((float)Convert.ToDouble(values[7]),
						(float)Convert.ToDouble(values[8]),
						(float)Convert.ToDouble(values[9]));
					// Now, the model was placed.
					model.IsPlaced = true;

					// Add the model into list.
					// Check type first.
					if (model.Type == ModelType.Road)
					{
						Roads.Add(model);
					}
					else
					{
						if (values.Length > 10)
						{
							for (int i = 10; i < values.Length; i++)
							{
								int index = Convert.ToInt32(values[i]);
								model.BoundingBoxMasterIndexes.Add(index);
								BBT.Leave[index].Models.Add(model);
							}
						}
						Models.Add(model);
					}
				}

				sr.Close();
			}
			catch
			{
				return;
			}
		}
		#endregion
		#endregion
	}
}
